home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 2784 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  1.9 KB

  1. Path: charnel.ecst.csuchico.edu!mcelroy
  2. From: mcelroy@ecst.csuchico.edu (James Robert McElroy)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: overloaded operator question
  5. Date: 19 Jan 1996 18:12:48 GMT
  6. Organization: California State University, Chico
  7. Message-ID: <4domv0$hfk@charnel.ecst.csuchico.edu>
  8. References: <4dmin1$160@noc2.drexel.edu>
  9. NNTP-Posting-Host: hairball.ecst.csuchico.edu
  10.  
  11. In article <4dmin1$160@noc2.drexel.edu>,
  12. Jonathan Juniman <st918h5w@dunx1.ocs.drexel.edu> wrote:
  13. >What is wrong with the following declaration:
  14. >
  15. >MATRIX.H
  16. >class Matrix
  17. >    {
  18. >    public:
  19. >    // several other functions here...
  20. >    Matrix Matrix::operator *(Matrix&, Matrix&);
  21. >    }
  22. >  
  23.  
  24. As has already been noted, when an overloaded binary operator
  25. is a class function,  the left operand is assumed to be an
  26. object of  the class itself.  You might look at it like:
  27.  
  28.        Matrix  Matrix::operator *  (this, Matrix &)  { .... }
  29.  
  30. You can call the overloaded operator using normal function syntax,
  31. which might also clarify the picture for you:
  32.  
  33.       Matrix foo(2, 4);
  34.           Matrix bar(4, 4);    
  35.           Matrix someMatrix(2,4);
  36.  
  37.       someMatrix = foo.operator*(bar);
  38.           // the same as someMatrix = foo + bar;
  39.  
  40. Just to clean things up a bit, seeing as how you are not altering
  41. either the left or right operand here, but instead returning a
  42. new (temporary) matrix as the result  of the operation, your
  43. method declaration should be:
  44.  
  45.     Matrix Matrix::operator * (const Matrix & right) const;
  46.  
  47. Your method should look something like:
  48.  
  49.      Matrix Matrix::operator * (const  Matrix & right) const
  50.      {
  51.         assert(columnDimension == right.rowDimension);
  52.     Matrix temp(rowDimension, right.columnDimension);
  53.  
  54.     // do matrix  multiplication here, assigning values
  55.     // to elements of temp.  Note that neither  the right
  56.     // or left operators are altered.
  57.  
  58.     return temp;
  59.       }
  60.  
  61.  
  62. -- 
  63. Jim McElroy
  64. Calif. State Univ., Chico
  65. mcelroy@ecst.csuchico.edu
  66.